﻿//https://leetcode.cn/problems/3sum/?envType=study-plan-v2&envId=top-100-liked

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums)
    {
        vector<vector<int>> ret;
        sort(nums.begin(), nums.end());
        //固定某一位
        for (int i = 0; i < nums.size();)
        {
            //不考虑正数 因为已经排序过 后面肯定无法凑成负数
            if (nums[i] > 0)
                break;
            int left = i + 1, right = nums.size() - 1, target = -nums[i];
            while (left < right)
            {
                int sum = nums[left] + nums[right];
                if (sum > target)
                    right--;
                else if (sum < target)
                    left++;
                else
                {
                    ret.push_back({ nums[left],nums[right],nums[i] });
                    //不漏
                    left++;
                    right--;
                    //去重
                    while (left < right && nums[left] == nums[left - 1])
                    {
                        left++;
                    }

                    while (left < right && nums[right] == nums[right + 1])
                    {
                        right--;
                    }

                }
            }
            i++;
            //固定的数字去重
            while (i < nums.size() && nums[i] == nums[i - 1])
                i++;
        }

        return ret;

    }
};